import React, {Component} from "react";
import {
    ActivityIndicator, DeviceEventEmitter,
    Dimensions,
    FlatList, Image,
    Platform,
    StyleSheet,
    Text,
    TouchableOpacity,
    View
} from "react-native";
import Header from "../../components/header";
import Constant from "../../utils/Constant";
import SeekItemView from "../seekCenter/seekComponents/SeekItemView";
import NoData from "../../utils/NoData";
import HttpUtils from '../../utils/HttpUtils';
import HttpUrls from '../../utils/HttpUrls';
import {CarSaleStatus, PermissionType} from "../../utils/Enum";
import AsyncImage from "../../components/image/AsyncImage";
import {
    getCarRegisterDate,
    getImgUrl,
    getMileFormat,
    getPerm,
    getPriceFormat,
    priceFenToYuanFormat
} from "../../utils/ComFunction";
import {ToastToUser} from "../../utils/CustomToast";
import LinearGradient from "react-native-linear-gradient";


const isIos = Platform.OS == 'ios';
const screenW = Dimensions.get('window').width;
const screenH = Dimensions.get('window').height;

let navigation;

export default class MyCarSourcePage extends Component {
    constructor( props){
        super(props);

        let priceOperatePerm = getPerm(PermissionType.Permission_EnableOfferPriceOperate)

        this.state = {
            priceOperatePerm,
            isFranchisee: Constant.userInfo.isFranchisee ? Constant.userInfo.isFranchisee : 0,//是否加盟商 0否1是

            offerPriceList: [],
            isRefresh: false,
            showFoot: 0, // 控制foot， 0：隐藏footer  1：已加载完成,没有更多数据   2 ：显示加载中
            pageNo: 1,
            pageSize: 10,
            keyword:  '',
            carTotal: 0,

            filterShowList: [],
        }
    }

    componentDidMount(){
        this.commonEvent = DeviceEventEmitter.addListener('commonEvent', (data) => {
            console.log('commonEvent', data);
            if (data.type == 'search' && data.fromPage == 'MyCarSourcePage') {

                let keywordObj = {
                    title: data.keyword,
                    key: 'keyword',
                    value: data.keyword
                }
                this.addFilter(keywordObj)

                this.setState({
                    keyword: data.keyword,
                }, function () {
                    this.refreshData()
                })
            }
        })
        this.getMyCarList()
    }

    componentWillUnmount(){
        if (this.commonEvent) {
            this.commonEvent.remove();
        }
    }

    render() {
        navigation = this.props.navigation;
        return (
            <View style={styles.container}>
                <Header navigation={navigation} Title={'我的车源'} RightButton={() => this.renderRightButton()} />

                {this.state.filterShowList.length > 0 && this.renderFilterShow()}

                {this.renderShare()}
                {this.offerPriceListData()}
            </View>
        )
    }

    renderFilterShow() {
        return (
            <View style={styles.filterShowContain}>
                {this.state.filterShowList.map((item, index) => {
                    if (item.key == 'clear') {
                        return (
                            <TouchableOpacity
                                key={index}
                                style={styles.filterShowItem}
                                onPress={() => {
                                    this.clearFilterShow()

                                }}>
                                <Image style={styles.filterShowClearImg} source={require('source/image/comm/btn_clear_history.png')}></Image>
                                <Text style={styles.filterShowText}>清空</Text>

                            </TouchableOpacity>
                        )
                    } else {
                        return (
                            <TouchableOpacity
                                key={index}
                                style={styles.filterShowItem}
                                onPress={() => {
                                    this.removeFilterShow(item, index)

                                }}>
                                <Text style={styles.filterShowText}>{item.title}</Text>
                                <Image style={styles.filterShowCloseImg} source={require('source/image/comm/icon_close.png')}></Image>
                            </TouchableOpacity>
                        )
                    }

                })
                }
            </View>
        )
    }

    addFilter(filterModel) {
        let filterShowList = this.state.filterShowList
        let clear = {
            key: 'clear',
        }
        if (filterShowList.length == 0) {
            filterShowList.push(filterModel)
            filterShowList.push(clear)

        } else {
            let isExist = false
            for (let i = 0; i < filterShowList.length; i++) {
                if (filterShowList[i].key == filterModel.key) {
                    isExist = true
                    filterShowList[i] = filterModel
                }
            }

            if (isExist) {

            } else {
                filterShowList.splice(filterShowList.length - 2, 0, filterModel);
                // filterShowList.push(filterModel)
            }
        }
        console.log('filterShowList', filterShowList)
        this.setState({
            filterShowList: filterShowList
        })
    }

    clearFilterShow() {
        this.setState({
            keyword: '',
            filterShowList: []
        }, function () {
            this.refreshData()
        })
    }

    removeFilterShow(item, index) {
        console.log('removeFilterShow', item)
        let filterShowList = this.state.filterShowList
        let temp = []
        for (let i = 0; i < filterShowList.length; i++) {
            if (i != index) {
                temp.push(filterShowList[i])
            }
        }

        if (item.key == 'keyword') {
            this.setState({
                keyword: ''
            })
        }

        if (temp.length == 1) {
            temp = []
        }

        this.setState({
            filterShowList: temp
        }, function () {
            this.refreshData()
        })
    }

    renderShare() {
        return (
            <View style={styles.shareContain}>
                <Text style={styles.totalText}>共找到{this.state.carTotal}辆</Text>
            </View>
        )
    }

    renderRightButton() {
        return (
            <View style={styles.topRightContain}>
                <TouchableOpacity
                    onPress={() => {
                        navigation.navigate('SearchPage', { fromPage: 'MyCarSourcePage', placeholder: '请输入车辆信息' })
                    }}>
                    <Image style={styles.iconImg} source={require('source/image/comm/icon_search_black.png')}></Image>
                </TouchableOpacity>
                <TouchableOpacity
                    style={{ marginLeft: 12}}
                    onPress={() => {
                        navigation.navigate('PublishCarPage');
                    }}>
                    <Image style={styles.iconImgAdd} source={require('source/image/imBottomMore.png')}></Image>
                </TouchableOpacity>
            </View>
        )
    }

    offerPriceListData(){
        return (
            <View
                style={{
                    flex: 1,
                    marginBottom: Constant.isIPhoneX ? Constant.bottomHeight + 0 : 0,
                }}>
                <FlatList
                    data={this.state.offerPriceList}
                    renderItem={this.renderItemView.bind(this)}
                    keyExtractor={item => item?.id || Math.random().toString()} // 使用唯一键
                    extraData={this.state}
                    onRefresh={this.refreshData}
                    refreshing={this.state.isRefresh}
                    ListEmptyComponent={this.renderEmpty.bind(this)}
                    ListFooterComponent={this.renderFooter.bind(this)}
                    onEndReached={this._onEndReached.bind(this)}
                    onEndReachedThreshold={0.1}
                />
            </View>
        );
    }

    renderItemView({item, index}) {
        return (
            <TouchableOpacity
                key={index}
                style={styles.cardContainer}
                activeOpacity={0.8}
                onPress={() => {
                    navigation.navigate('CarDetailPage', {
                        carId: item.carId,
                        saleStatus: item.saleStatus,
                        merchantId: item.merchantId,
                        carDetailCallBack: () => {
                            this.refreshData()
                        }
                    })
                }}
            >

                {/*<View style={{ backgroundColor: '#f6f6f6', height: 1 }}></View>*/}

                <View style={styles.carContainer}>

                    <View style={styles.labelBox}>
                        {
                            item.detectionStatus == 3 ?
                                <Image style={{ width: 59, height: 18, marginRight: 4 }} source={require('source/image/detection_auth.png')} />
                                :
                                null
                        }

                        {
                            item.isReported == 1 ?
                                <View style={[styles.labelItemBox, { backgroundColor: '#FFF5E6' }]}>
                                    <Text style={[styles.labelText, { color: '#F99802' }]}>有维保</Text>
                                </View>
                                :
                                null
                        }

                        {
                            item.saleStatus == CarSaleStatus.CarSaleStatusReserved ?
                                <View style={[styles.labelItemBox, { backgroundColor: '#F1FAED' }]}>
                                    <Text style={[styles.labelText, { color: '#6ECC49' }]}>已预订</Text>
                                </View>
                                :
                                null
                        }

                    </View>

                    <AsyncImage
                        source={{ uri: getImgUrl(item.mainPic) }}
                        defaultSource={require('source/image/icon_car_default.png')}
                        style={styles.carImage}
                        resizeMode="cover"
                    />

                    <View style={styles.infoContainer}>
                        <View>
                            <Text style={styles.carName} numberOfLines={1} ellipsizeMode='tail'>{item.seriesName + ' ' + item.speciesName}</Text>

                            <Text style={styles.subInfo}>
                                {this.getSubCarInfo(item)}
                            </Text>
                        </View>


                        <View style={styles.priceContain}>
                            <Text style={styles.price}>
                                {getPriceFormat(item.purchasePrice)}
                            </Text>
                        </View>

                    </View>
                </View>
            </TouchableOpacity>
        );
    }


    //刷新数据
    refreshData = () => {
        console.log('刷新数据')
        this.setState(
            {
                isRefresh: true,
                pageNo: 1,
                offerPriceList: [],
                showFoot: 1,
                // keyword: '',
            },
            function () {
                this.getMyCarList();
            },
        );
    }

    renderEmpty() {
        return <NoData Desc="暂无数据" style={{marginTop: gREM(100)}} />;
    }

    // 底部加载更多
    renderFooter() {
        if (this.state.showFoot === 1) {
            return null;
        } else if (this.state.showFoot === 2) {
            return (
                <View style={styles.footer}>
                    <ActivityIndicator size="small" color="#999999" />
                    <Text style={styles.loadMoreTextStyle}>正在加载更多数据...</Text>
                </View>
            );
        } else if (this.state.showFoot === 0) {
            return null;
        }
    }

    _onEndReached() {
        if(this.state.offerPriceList.length == 0){
            return null;
        }
        //如果是正在加载中或没有更多数据了，则返回
        if (this.state.showFoot == 1) {
            return null;
        }
        //底部显示正在加载更多数据
        this.setState(
            {
                showFoot: 2,
                pageNo: this.state.pageNo + 1,
            },
            function () {
                this.getMyCarList();
            },
        );
    }

    // 获取我的车源
    getMyCarList() {
        let params = {
            pageNo: this.state.pageNo,
            pageSize: this.state.pageSize,
            carName: this.state.keyword,
        }

        params['searchChannel'] = 'external_query_car'

        HttpUtils.postRequest(HttpUrls.searchCars, params)
            .then((result) => {

                let code = result.code
                if (code == 0) {

                    let resultList = result.data.resultList

                    console.log('resultList', resultList)
                    if (resultList.length > 0) {
                        this.setState({
                            showFoot: 2,
                            offerPriceList: this.state.offerPriceList.concat(resultList),
                        })
                        if(result.data.totalSize < 5){
                            this.setState({
                                showFoot: 1,
                            })
                        }
                    } else {
                        this.setState({
                            showFoot: 1,  // 加载完成
                        })
                    }

                    this.setState({
                        carTotal: result.data.totalSize,
                        isRefresh: false,
                    })
                } else {
                    this.setState({
                        isRefresh: false,

                    })
                }
            })
            .catch((error) => {
                this.setState({
                    isRefresh: false,

                })
            });
    }

    getSubCarInfo(item) {

        let carInfoStr = ''
        if (item.registerDate && item.registerDate != null) {
            carInfoStr = getCarRegisterDate(item.registerDate)
        }

        if (item.mileage && item.mileage != 0) {
            carInfoStr = carInfoStr + ' | ' + getMileFormat(item.mileage)
        }

        if (item.cityName && item.cityName != '') {
            if (carInfoStr != '') {
                carInfoStr = carInfoStr + ' | ' + item.cityName
            } else {
                carInfoStr = item.cityName
            }

        }

        return carInfoStr
    }

}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#f5f5f5',
    },

    // 右侧搜索样式
    topRightContain: {
        paddingRight: 12,
        width: '100%',
        height: '100%',
        flexDirection: 'row',
        justifyContent: 'flex-end',
        alignItems: 'center',
    },
    iconImg: {
        width: 24,
        height: 24
    },
    iconImgAdd: {
        width: 21,
        height: 21
    },


    cardContainer: {
        backgroundColor: '#fff',
        paddingHorizontal: 15,
        paddingBottom: 15,
        marginTop: 10,
        flexDirection: 'column',
        width: '100%',
    },
    carContainer: {
        flexDirection: 'row',
        alignItems: 'center',
        marginTop: 10,
    },
    carImage: {
        width: 120,
        height: 85,
        borderRadius: 4,
        backgroundColor: '#f5f5f5',
    },
    infoContainer: {
        flex: 1,
        marginLeft: 8,
        height: 76,
        flexDirection: 'column',
        justifyContent: 'space-between',
    },
    carName: {
        fontSize: 14,
        fontWeight: '500',
        marginBottom: 5,
        color: '#333',
    },
    subInfo: {
        fontSize: 12,
        color: '#999999',
        marginTop: 3,
    },
    price: {
        fontSize: 14,
        color: '#ED542E',
        fontWeight: '500',
    },
    priceContain: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
    },

    labelBox: {
        zIndex: 1000,
        position: 'absolute',
        left: 4,
        top: 4,
        flexDirection: 'row',
        justifyContent: 'flex-start',
        alignItems: 'center'
    },
    labelItemBox: {
        marginRight: 4,
        paddingHorizontal: 6,
        height: 18,
        flexDirection: 'row',
        alignItems: 'center',
        borderRadius: 2,
        backgroundColor: '#F4F4F4'
    },
    labelText: {
        fontSize: 10,
        color: '#FF7B00'
    },

    footer: {
        flexDirection: 'row',
        height: 40,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#f6f6f6'
    },
    loadMoreTextStyle: {
        fontSize: 14,
        color: '#999999',
        marginStart: 10,
    },

    shareContain: {
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'space-between',
        backgroundColor: '#fff',
        height: 32,
        paddingHorizontal: 15
    },
    totalText: {
        fontSize: 14,
        color: '#666666'
    },

    // 搜索样式
    filterShowContain: {
        flexDirection: 'row',
        flexWrap: 'wrap',
        backgroundColor: '#fff',
        paddingHorizontal: 15
    },
    filterShowItem: {
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'center',
        height: 30,
        backgroundColor: '#f6f6f6',
        borderRadius: 4,
        paddingHorizontal: 10,
        marginRight: 10,
        marginBottom: 5
    },
    filterShowText: {
        fontSize: 13,
        color: '#696969'
    },
    filterShowCloseImg: {
        width: 12,
        height: 12,
        marginLeft: 2
    },
    filterShowClearImg: {
        width: 14,
        height: 14,
        marginRight: 2,
        resizeMode: 'contain'
    },

})